package com.skyline.base.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.skyline.base.dao.NoticeDao;
import com.skyline.base.model.Notification;
import com.skyline.base.service.NoticeService;
import com.skyline.base.type.NotificationType;

@Service("noticeService")
public class NoticeServiceImpl implements NoticeService {

	@Autowired
	private NoticeDao noticeDao;

	@Override
	public List<Notification> getNotificationByOwnerId(Long ownerId) {
		List<Notification> unsortedNotifs = noticeDao.findNotificationByOwnerId(ownerId);
		List<Notification> sortedNotifs = new ArrayList<Notification>();
		for (Notification notif : unsortedNotifs) {
			Notification sameNotif = getSameNotif(notif, sortedNotifs);
			if (sameNotif == null) {
				sortedNotifs.add(notif);
			} else {
				sortedNotifs.remove(sameNotif);
				if (sameNotif.getNotifierId() != notif.getNotifierId()) {
					sameNotif.setSecondNotifierId(notif.getNotifierId());
					sameNotif.setSecondNotifierNickname(notif.getNotifierNickname());
				}
				sortedNotifs.add(sameNotif);
			}
		}
		return sortedNotifs;
	}

	private Notification getSameNotif(Notification notif, List<Notification> sortedNotifs) {
		for (Notification sortedNotif : sortedNotifs) {
			if (sortedNotif.getResourceId().equals(notif.getResourceId()) && sortedNotif.getType().equals(notif.getType())) {
				return sortedNotif;
			}
		}
		return null;
	}

	@Override
	public Notification getNotificationById(Long id) {
		Notification notification = noticeDao.findNotificationById(id);
		if (notification == null) {
			return null;
		} else {
			noticeDao.deleteNotificationByResource(notification.getOwnerId(), notification.getResourceId(), notification.getType());
			return notification;
		}
	}

	@Override
	public void addNotication(Long ownerId, Long notifierId, String notifierNickname, String resourceId, String resourceTitle,
			NotificationType type) {
		noticeDao.insertNotication(ownerId, notifierId, notifierNickname, resourceId, resourceTitle, type);

	}

	// @Override
	// public void deleteNotificationById(Long id) {
	// noticeDao.deleteNotificationById(id);
	// }

	// @Override
	// public void deleteNotificationByResource(Long resourceId,
	// NotificationType type) {
	// noticeDao.deleteNotificationByResource(resourceId, type);
	// }

}
